package WarTug;

import java.util.ArrayList;
import java.util.HashMap;

//Handles all interactions with units (TODO:Decide if this is only client-side or not), whether it be adding/removing units or unit movement logic

public class UnitManager {
	private HashMap<Integer,SimpleUnit> allUnits; //All units currently tracked client-side
	private ArrayList<SimpleUnit> newUnits; //All units received from the server this tick, reset at beginning of each tick
	private ArrayList<SimpleUnit> deadUnits; //Units tracked for animation of death
	private GraphicsManager gManager;
	
	public UnitManager(GraphicsManager gMan) {
		gManager = gMan;
		allUnits = new HashMap<Integer,SimpleUnit>();
		newUnits = new ArrayList<SimpleUnit>();
		deadUnits = new ArrayList<SimpleUnit>();
	}
	
	public void resetUnitLists() { //Call at the beginning of each game to flush these lists
		allUnits = new HashMap<Integer,SimpleUnit>();
		newUnits = new ArrayList<SimpleUnit>();
		deadUnits = new ArrayList<SimpleUnit>();
	}
	
	public void addUnit(SimpleUnit s){ //Adds unit s to the newUnits List
		synchronized(newUnits) {
			newUnits.add(s);
		}
	}
	
	private void moveUnitToDeadList(SimpleUnit s) {
		allUnits.remove(s.uid);
		//deadUnits.add(s);//TODO: Re-add this if we are ever doing anything with death animations
	}
	
	private void updateAllUnitList() {
		ArrayList<SimpleUnit> temp = newUnits;
		synchronized(newUnits) { //Synchronized method, so client thread can't update the old newUnitList
			newUnits = new ArrayList<SimpleUnit>();
		}
		for (SimpleUnit unit: temp){
			if (unit!=null){ //Sometimes error occurs and unit is null?
				if (unit.isDead && allUnits.containsKey(new Integer(unit.uid))){
					gManager.removeDrawableEntity(allUnits.get(unit.uid)); //TODO: Remove this if we are ever doing anything with death animations
					moveUnitToDeadList(unit);
				} else if (allUnits.containsKey(new Integer(unit.uid))) {
					allUnits.get(new Integer(unit.uid)).modify(unit); //Updates unit if already stored in allUnits
				} else {
					allUnits.put(new Integer(unit.uid), unit); //Otherwise adds new unit to list of units
					gManager.addDrawableEntity(unit); //Also adds it to the list of things the gManager will draw
				}
			}
		}
	}
	
	private void moveUnits(long delta) {
		for (int i : allUnits.keySet())
		{
			allUnits.get(i).move(delta);
		}
	}
	
	public void updateUnits(long delta) {
		updateAllUnitList();
		moveUnits(delta);
	}
}
